<!--
 * @Author: t-xiangqun.li t-xiangqun.li@pcitc.com
 * @Date: 2025-10-21 15:31:26
 * @LastEditors: lixiangqun
 * @LastEditTime: 2025-11-16 18:08:25
 * @FilePath: \electrconVue\src\views\Conversation.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div
    class="flex h-[10%] items-center justify-between bg-gray-200 border-b border-gray-300 px-3"
  >
    <div>{{ conversation?.title }}</div>
    <div>{{ conversation?.createdAt }}</div>
  </div>
  <div class="w-[80%] h-[75%] overflow-y-auto mx-auto">
    <MessageList :messages="filterMessage" ref="messageListRef" />
  </div>
  <div class="w-[80%] h-[15%] flex items-center mx-auto">
    <MessageInput
      :disabled="messageStore.isMessageLoading"
      v-model:inputValue="inputValue"
      @create="onCreate"
    />
  </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, ref, watch } from "vue";
import MessageList from "../components/MessageList.vue";
import MessageInput from "../components/MessageInput.vue";
import { MessageProps, MessageStatus, MessageListProps } from "../types";
import { db } from "../db";
import { useRoute } from "vue-router";
import { useConversationStore } from "../stores/conversation";
import { useMessageStore } from "../stores/message";
const route = useRoute();
const conversationId = ref(parseInt(route?.query?.id as string));
const initMessageId = parseInt(route.query.init as string);
const inputValue = ref<string>("");
const conversationStore = useConversationStore();
const messageStore = useMessageStore();
const conversation = computed(() =>
  conversationStore.getConversationById(conversationId.value)
);
const filterMessage = computed(() => {
  return messageStore.items;
});

const sendMessages = computed(() => {
  return filterMessage.value
    .filter((item) => item.status !== "loading")
    .map((item) => ({
      role: item.type === "question" ? "user" : "assistant",
      content: item.content,
      ...(item.imagePath && { imagePath: item.imagePath }),
    }));
});

const messageListRef = ref<MessageListProps>();
// 初始化创建聊天信息
const createInitMessage = async () => {
  // loading数据
  const createData: Omit<MessageProps, "id"> = {
    content: "",
    type: "answer",
    status: "loading",
    conversationId: conversationId.value,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  };
  // 新消息loading的messageId
  const newMessageId = await messageStore.createMessage(createData);
  await messageScrollBottom();
  // 消息中填入loading
  if (conversation.value) {
    const provider = await db.providers
      .where({ id: conversation.value?.providerId })
      .first();
    // 获取到会话的ai提供者
    if (provider) {
      // 开始建立AI对话
      await window.electronAPI.startChat({
        // content: lastQuestion.value?.content || "",
        messages: sendMessages.value || [],
        messageId: newMessageId,
        providerName: provider.name,
        selectedModel: conversation.value.selectedModel,
      });
    }
  }
};
let copiedImagePath: string | null;
const onCreate = async (value: string, imagePath?: string) => {
  if (value) {
    if (imagePath) {
      try {
        copiedImagePath =
          await window.electronAPI.copyImageToUserDir(imagePath);
        console.log(copiedImagePath, "复制后地址"); //C:\Users\15478\AppData\Roaming\electron-ai\images\icon.png 复制后地址
      } catch (error) {
        console.error("复制错误", error);
      }
    }
    const date = new Date().toISOString();
    await messageStore.createMessage({
      content: value,
      type: "question",
      conversationId: conversationId.value,
      createdAt: date,
      updatedAt: date,
      ...(copiedImagePath && { imagePath: copiedImagePath }),
    });
    inputValue.value = "";

    createInitMessage();
  }
};

const messageScrollBottom = async () => {
  await nextTick();
  if (messageListRef.value) {
    messageListRef.value.ref.scrollIntoView({
      block: "end",
      behavior: "smooth",
    });
  }
};
onMounted(async () => {
  // 进入会话，会生成会话id，通过会话id拿到对应的聊天message
  await messageStore.fetchMessageByConversationId(conversationId.value);
  await messageScrollBottom();
  // 第一次建立会话时，获取最后一条message，即问题
  if (initMessageId) {
    // 创建初始化信息loading
    await createInitMessage();
  }
  const checkAndScrollToBottom = async () => {
    let initMessageListHeight = 0;
    if (messageListRef.value) {
      const newHeight = messageListRef.value.ref.clientHeight;
      if (newHeight > initMessageListHeight) {
        initMessageListHeight = newHeight;
        await messageScrollBottom();
      }
    }
  };
  // 监听并更新AI回答的结果
  let streamContent = "";
  window.electronAPI.onUpdateMessage(async (streamData) => {
    const { messageId, data } = streamData;
    // 获取到当前的消息，即loading消息的id
    streamContent = streamContent + data.result;
    const updatedMessage = {
      content: streamContent,
      status: (data.is_end ? "finished" : "streaming") as MessageStatus,
      updatedAt: new Date().toISOString(),
    };
    if (data.is_end) {
      streamContent = "";
    }
    await messageStore.updateMessage(messageId, updatedMessage);
    await nextTick();
    checkAndScrollToBottom();
  });
});

watch(
  () => route.query.id,
  async (newVal: string) => {
    const id = parseInt(newVal);
    conversationId.value = id;
    await messageStore.fetchMessageByConversationId(id);
    await messageScrollBottom();
  }
);
</script>
